<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 16-3-8
 * Time: 下午12:28
 */

namespace Admin\Controller;
use Think\Page;
use Think\Upload;
use Think\Model;
class MemberController extends AdminController {
    public function _initialize(){
        parent::_initialize();
    }
    /**
     * 会员列表
     */
    public function index(){
        $email = I('email');
        $member_id=I('member_id');
		$name = I('name');
		$phone = I('phone');
        if(!empty($email)){
            $where['email'] = array('like','%'.$email.'%');
        }
        if (!empty($member_id)){
            $where['member_id']=$member_id;
        }
        if(!empty($name)){
			 $where['name'] = array('like','%'.$name.'%');
		}
		if(!empty($phone)){
			$where['phone'] = array('like','%'.$phone.'%');
		}
		$admin=M('Admin')->where('admin_id = '.$_SESSION['admin_userid'])->find();
		if($admin['level']==3){
			$where['pid']=$_SESSION['admin_userid'];
		}else if($admin['level']==2){
			$zhike=M('Admin')->where('parent_id ='.$_SESSION['admin_userid'])->select();
			foreach ($zhike as $k =>$v){
				$arr=array($v['admin_id']);
			}
			$where['pid']=array('in',$arr);
		}
        $count      =  M('Member')->where($where)->count();// 查询满足要求的总记录数

        $Page       = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)

        //给分页传参数
        setPageParameter($Page, array('email'=>$email,'member_id'=>$member_id,'name'=>$name,'phone'=>$phone));

        $show       = $Page->show();// 分页显示输出
        
        $list =  M('Member')
            ->where($where)
            ->order(" member_id desc ")
            ->limit($Page->firstRow.','.$Page->listRows)
        	->select();
        
        //统计会员总量
		$member_sum = M('Member')->count();
		$member_ok = M('Member')->where("`status`=1")->count();
		/*  foreach ($list as $k =>$v){
			$where['member_id']=$v['member_id'];
			$where['status']=1;
			$pay=M('Pay')->where($where)->select();
			$pay_money=0;
			foreach ($pay as $kk=>$vv){
				$pay_money+=$vv['money'];
			}
			$where3['member_id']=$v['member_id'];
			$where3['status']=array('in','0,1');
			//$where3['type']='buy';
			$order=M('Orders')->where($where3)->select();
			$order_money=0;
			foreach ($order as $kkk=>$vvv){
				$order_money+=($vvv['num']-$vvv['trade_num'])*$vvv['price'];
			}
			$trade_buy=0;
			$trade_sell=0;
			$where_buy=" where member_id = ".$v['member_id']." and type = 'buy' ";
			$sql1=$this->getTradeSql($where_buy);
			$Model=new Model();
			//$sql1 = $sql." where member_id = ".$v['member_id']." and type = 'buy' ";
			$r=$Model->query($sql1);
			//dump($sql1);
			//dump($trade_buy);
			foreach($r as $k1=>$v1){
				$trade_buy+=$v1['money'];
			}
			//dump($trade_buy);
			$where_sell=" where member_id = ".$v['member_id']." and type = 'sell' ";
			$sql2=$this->getTradeSql($where_sell);
			//$sql2= $sql." where member_id = ".$v['member_id']." and type = 'sell' ";
			$r2=$Model->query($sql2);
			//dump($sql2);
			//dump($trade_sell);
			foreach ($r2 as $k2=>$v2){
				$trade_sell+=$v2['money'];
			}
			$chicang_money=0;
			$user_currency=M('Currency_user')->where('member_id = '.$v['member_id'])->select();
			
			foreach ($user_currency as $k3 =>$v3){
				$new_price=M('Trade_'.$v3['currency_id'])->order('add_time desc')->find()['price'];
				//dump($new_price);
				$chicang_money+=$new_price*$v3['num'];
				
			}
			//dump($chicang_money);
			//dump($trade_sell);
			$member_money=$v['rmb']+$v['forzen_rmb'];
			//dump($trade_sell);dump($trade_buy);dump($chicang_money);dump($order_money);
			//dump($member_money);dump($order_money);dump($trade_buy);dump($trade_sell);dump($pay_money);
			$list[$k]['all_profit']=round($trade_sell-$trade_buy+$chicang_money+$order_money,2);
			$withdraw=M('withdraw')->where('status = 3 and uid = '.$v['member_id'])->sum('all_money');
			$list[$k]['access_money']=$withdraw+$v['rmb'];
			$list[$k]['chicang_money']=$order_money;
			
		}  */
		//dump($list);
// 		foreach($list as $k=>$v){
// 			$list[$k]['teamsum'] = $this->daishu2($v['member_id'],20);
// 			//$list[$k]['teamsum'] = count($counta)?count($counta):0;
// 		}
		$rmb = M('Member')->where( $where )->sum('rmb');
		$forzen_rmb = M('Member')->where( $where )->sum('forzen_rmb');
		$num = $rmb+$forzen_rmb;
		$this->assign('num',$num);
		$this->assign('rmb',$rmb);
		$this->assign('forzen_rmb',$forzen_rmb);
		$this->assign('member_sum',$member_sum);
		$this->assign('member_ok',$member_ok);
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display(); // 输出模板
    }
    public function getTradeSql($where){
    	$currency=M('Currency')->where('is_line = 1')->select();
    	foreach ($currency as $k =>$v){
    		$arr[]=$v['currency_id'];
    	}
    	for($i=0;$i<count($arr);$i++){
    		$sql_union_all .=
    		"select * from yang_trade_".$arr[$i]."
			as t".$arr[$i].$where."
			 union all ";
    	}
    	$sql = substr($sql_union_all,0,-10);
    	return $sql;
    }
	//查询团队人数
	protected function daishu($items,$lv){

		

		for($i=0;$i<$lv;$i++){
			$where['pid']=array("in",$items);
			$user=M("Member")->where($where)->select();
			if(empty($user)){
				continue;
			}
			foreach ($user as $key=>$vo){
				$name[] =  (string)($vo['member_id']);
			}
			$r = $items = $name;
		}
		return array_unique($r);
	}
	
	private function daishu2($member_id,$lv,&$count=0){
		$where['pid'] = array('in',$member_id);
		$info = M('Member')->Field('member_id')->where($where)->select();
		$count += count($info);
		$member = array_column($info,'member_id');
		if(!empty($member)){
			$this->daishu2($member,$lv,$count);
		}
		return $count;
	}
	
	
	
    /**
     * 添加会员
     */
    public function addMember(){
        if(IS_POST){
            $M_member = D('Member');
            $_POST['ip'] = get_client_ip();
            $_POST['reg_time'] = time();
            if($r = $M_member->create()){
                if($r['pwd']==$r['pwdtrade']){
                    $this->error('支付密码不能和密码一样');
                    return;
                }
                if($M_member->add($r)){
                    $this->success('添加成功',U('Member/index'));
                    return;
                }else{
                    $this->error('服务器繁忙,请稍后重试');
                    return;
                }
            }else{
                $this->error($M_member->getError());
                return;
            }
        }else{
            $this->display();
        }
    }
    /**
     * 添加个人信息
     */
    public function saveModify(){
        $member_id = I('get.member_id','','intval');
        $M_member = D('Member');
        if(IS_POST){
            $_POST['status'] = 1;//0=有效但未填写个人信息1=有效并且填写完个人信息2=禁用
            if (!$data=$M_member->create()){ // 创建数据对象
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $this->error($M_member->getError());
                return;
            }else {
                $where['member_id'] = $_POST['member_id'];
                $r = $M_member->where($where)->save();
                if($r){
                    $this->success('添加成功',U('Member/index'));
                    return;
                }else{
                    $this->error('服务器繁忙,请稍后重试');
                    return;
                }
            }
        }else{
            $where['member_id'] = $member_id;
            $list = $M_member->where($where)->find();
            $this->assign('list',$list);
            $this->display();
        }
    }
    /**
     * 显示自己推荐列表
     */
    public function show_my_invit(){
        $member_id = $_GET['member_id'];
        if(empty($member_id)){
            $this->error('参数错误');
            return;
        }
        $M_member = M('Member');
        $count      = $M_member->where(array('pid'=>$member_id))->count();// 查询满足要求的总记录数
        $Page       = new Page($count,25);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $my_invit = $M_member
            ->where(array('pid'=>$member_id))
            ->order(" reg_time desc ")
            ->limit($Page->firstRow.','.$Page->listRows)->select();
        if($my_invit){
            $this->assign('my_invit',$my_invit);
            $this->assign('page',$show);// 赋值分页输出
            $this->display(); // 输出模板
        }else{
            $this->error('抱歉,您还没有推荐其他人');
            return;
        }
    }
    /**
     * 修改会员
     */
    public function saveMember(){
        $member_id = I('get.member_id','','intval');
        $M_member = M('Member');
        if(IS_POST){
            $member_id = I('post.member_id','','intval');
            $where['member_id'] = $member_id;
            $list = $M_member->where($where)->find();
            //头像上传
            $upload = new Upload();// 实例化上传类
            $upload->maxSize   =     3145728 ;// 设置附件上传大小
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
            $upload->savePath  =     'Member/Head/'; // 设置附件上传（子）目录
            // 上传文件
            if(!$_FILES['head']['error']){
                $info   =   $upload->upload();
                $file_path = ltrim($upload->rootPath.$info['head']["savepath"].$info['head']["savename"],'.');
            }
            $_POST['head'] = empty($file_path)?I('post.headold'):$file_path;
            //头像上传end
            if($_POST['pwd'] == $_POST['pwdtrade'] && $_POST['pwd']!=null ){
                $this->error('交易密码不能和密码一致');
                return;
            }
            if($_POST['nick']!=$list['nick']){
                $where = null;
                $where['member_id']  = array('NEQ',$member_id);
                $where['nick'] = $_POST['nick'];
                if($M_member->field('nick')->where($where)->select()){
                    $this->error('昵称重复');
                    return;
                }
            }
            if($_POST['phone']!=$list['phone']){
                $where = null;
                $where['member_id']  = array('NEQ',$member_id);
                $where['phone'] = $_POST['phone'];
                if($M_member->field('phone')->where($where)->select()){
                    $this->error('手机号重复');
                    return;
                }
            }
            $_POST['pwd'] =  $_POST['pwd']?I('post.pwd','','md5'):$list['pwd'];
            $_POST['pwdtrade'] = $_POST['pwdtrade']?I('post.pwdtrade','','md5'):$list['pwdtrade'];
            $r = $M_member->save($_POST);
            if($r!==false){
                $this->success('修改成功',U('Member/index'));
                return;
            }else{
                $this->error('修改失败');
                return;
            }
        }else{
            if($member_id){
                $where['member_id'] = $member_id;
                $list = $M_member->where($where)->find();
                $this->assign('list',$list);
                $this->display();
            }else{
                $this->error('参数错误');
                return;
            }
        }
    }
    /**
     * 删除会员
     */
    public function delMember(){
        $member_id = I('get.member_id','','intval');
        $M_member = M('Member');
        //判断还有没有余额
		$table_p = $member_id % 10;
        $where['member_id']= $member_id;
        $member = $M_member->where($where)->find();
        $member_currency = M('Currency_user')->where($where)->find();
        if($member['rmb']>0||$member['forzen_rmb']>0||$member_currency['num']>0||$member_currency['forzen_num']>0){
            $this->error('因账户有剩余余额,禁止删除');
            return;
        }
        $r[] = $M_member->delete($member_id);
        $r[] = M('Currency_user')->where($where)->delete();
        $r[] = M('Finance_'.$table_p)->where($where)->delete();
        $r[] = M('Orders')->where($where)->delete();
		foreach($this->currency as $k => $v){
			$r[] = M('Trade_'.$v['currency_id'])->where($where)->delete();
		}
        
        $r[] = M('Withdraw')->where('uid='.$member_id)->delete();
        $r[] = M('Pay')->where($where)->delete();
        if($r){
            $this->success('删除成功',U('Member/index'));
            return;
        }else{
            $this->error('删除失败');
            return;
        }
    }
    public function modifyMember(){
    	$member_id = I('get.member_id','','intval');
    	$where['member_id']=$member_id;
    	$data['status']=3;
    	$r=M('Member')->where($where)->save($data);
    	if($r){
            $this->success('通过审核成功',U('Member/index'));
            return;
        }else{
            $this->error('通过审核失败');
            return;
        }
    }
    /**
     * ajax判断邮箱
     * @param $email
     */
    public function ajaxCheckEmail($email){
        $email = urldecode($email);
        $data = array();
        if(!checkEmail($email)){
            $data['status'] = 0;
            $data['msg'] = "账号格式错误";
        }else{
            $M_member = M('Member');
            $where['email']  = $email;
            $r = $M_member->where($where)->find();
            if($r){
                $data['status'] = 0;
                $data['msg'] = "账号已存在";
            }else{
                $data['status'] = 1;
                $data['msg'] = "";
            }
        }
        $this->ajaxReturn($data);
    }

    /**
     * ajax验证昵称是否存在
     */
    public function ajaxCheckNick($nick){
        $nick = urldecode($nick);
        $data =array();
        $M_member = M('Member');
        $where['nick']  = $nick;
        $r = $M_member->where($where)->find();
        if($r){
            $data['msg'] = "昵称已被占用";
            $data['status'] = 0;
        }else{
            $data['msg'] = "";
            $data['status'] = 1;
        }
        $this->ajaxReturn($data);
    }
    /**
     * ajax手机验证
     */
    function ajaxCheckPhone($phone) {
        $phone = urldecode($phone);
        $data = array();
        if(!checkMobile($phone)){
            $data['msg'] = "手机号不正确！";
            $data['status'] = 0;
        }else{
            $M_member = M('Member');
            $where['phone']  = $phone;
            $r = $M_member->where($where)->find();
            if($r){
                $data['msg'] = "此手机已经绑定过！请更换手机号";
                $data['status'] = 0;
            }else{
                $data['msg'] = "";
                $data['status'] = 1;
            }
        }
        $this->ajaxReturn($data);
    }
    
    /**
     * 查看个人币种
     */
    public function show(){
    	$currency = M('Currency_user');
    	$member = M('Member');
    	$member_id = I('member_id');
    	if(empty($member_id)){
    		$this->error('参数错误',U('Member/index'));
    	}
    	$where['member_id'] = $member_id;
    	
    	$count = $currency->join(C("DB_PREFIX")."currency ON ".C("DB_PREFIX")."currency_user.currency_id = ".C("DB_PREFIX")."currency.currency_id")
    			->where($where)->count();
    	$Page = new \Think\Page ( $count,20); // 实例化分页类 传入总记录数和每页显示的记录数
    	$show = $Page->show();//分页显示输出性
    	$info = $currency->join(C("DB_PREFIX")."currency ON ".C("DB_PREFIX")."currency_user.currency_id = ".C("DB_PREFIX")."currency.currency_id")
    			->where($where)->limit($Page->firstRow.','.$Page->listRows)
    			->select();
    	$member_info = $member->field('member_id,name,phone,email,rmb,forzen_rmb')->where($where)->find();
    	
    	$this->assign('member_info',$member_info);
    	$this->assign('info',$info);
    	$this->assign('page',$show);
    	$this->display();
    }
    //修改个人币种数量
    public function updateMemberMoney(){
    	$member_id=I('post.member_id');
    	$currency_id=I('post.currency_id');
    	$num=I('post.num');
    	$forzen_num=I('post.forzen_num');
    	if(empty($member_id)||empty($member_id)){
    		$data['info']="参数不全";
    		$data['status']=0;
    	}
    	$where['member_id']=$member_id;
    	$where['currency_id']=$currency_id;
    	$r[]=M('Currency_user')->where($where)->setField('num',$num);
    	$r[]=M('Currency_user')->where($where)->setField('forzen_num',$forzen_num);
    	if($r){
    		$data['info']="修改成功";
    		$data['status']=1;
    	}else{
    		$data['info']="修改失败";
    		$data['status']=0;
    	}
    	$this->ajaxReturn($data);
    }
    
 public function updateRmb(){
 	$member_id=I('member_id');
 	$rmb=I('rmb');
 	$forzen_rmb=I('forzen_rmb');
 	$data['rmb']=$rmb;
 	$data['forzen_rmb']=$forzen_rmb;
 	$where['member_id']=$member_id;
 	$r=M('Member')->where($where)->save($data);
 	if($r){
 		$arr['status']=1;
 		$arr['info']="修改成功";
 	}else{
 		$arr['status']=0;
 		$arr['info']="修改失败";
 	}
 	$this->ajaxReturn($arr);
 }
    
}